import { Button, NavBar, Form, Input, Toast } from 'antd-mobile'
import { useDispatch } from 'react-redux'
import { login, getCode } from '@/store/actions/login'
import { useHistory, useLocation } from 'react-router-dom'
import { AxiosError } from 'axios'
import { useRef } from 'react'
import { InputRef } from 'antd-mobile/es/components/input'
import { useState } from 'react'
import { useEffect } from 'react'
import styles from './index.module.scss'

type LoginForm = { mobile: string; code: string }

const Login = () => {
  const dispatch = useDispatch<any>()
  const location = useLocation<{ from: string } | undefined>()
  console.log(location.state, location.state?.from)

  const [form] = Form.useForm()
  const history = useHistory()
  const mobileRef = useRef<InputRef>(null)
  const [timeLeft, setTimeLeft] = useState(0)

  const timerRef = useRef(-1)
  const onGetCode = () => {
    const mobile = form.getFieldValue('mobile') as string | undefined

    const hasError = form.getFieldError('mobile').length

    const content = mobile?.trim()
    if (!content?.length || hasError) {
      mobileRef.current?.focus()
      return
    }

    dispatch(getCode(mobile!))
    setTimeLeft(60)

    timerRef.current = window.setInterval(() => {
      setTimeLeft((timeLeft) => timeLeft - 1)

      console.log('定时器执行了')
    }, 1000)

    Toast.show({
      content: '验证码已发送!',
      duration: 1000,
    })
  }

  useEffect(() => {
    if (timeLeft <= 0) {
      window.clearInterval(timerRef.current)
    }
  }, [timeLeft])

  useEffect(() => {
    return () => {
      window.clearInterval(timerRef.current)
    }
  }, [])

  const onFinish = async (values: LoginForm) => {
    try {
      await dispatch(login(values))

      Toast.show({
        content: '登陆成功',
        duration: 1000,
        afterClose: () => {
          history.replace(location.state?.from ?? '/home')
        },
      })
    } catch (e) {
      const error = e as AxiosError<{ message: string }>

      Toast.show({
        content: error.response?.data.message,
      })
    }
  }
  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}></NavBar>

      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form
          form={form}
          // initialValues={{
          //   mobile: '13911112222',
          //   code: '246810',
          // }}
          // validateTrigger={['onBlur']}
          onFinish={onFinish}
        >
          <Form.Item
            className="login-item"
            name="mobile"
            // validateTrigger="onBlur"
            rules={[
              { required: true, message: '请输入手机号' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号格式错误',
              },
            ]}
          >
            <Input
              ref={mobileRef}
              maxLength={11}
              placeholder="请输入手机号"
              autoComplete="off"
            ></Input>
          </Form.Item>

          <Form.Item
            className="login-item"
            name="code"
            // validateTrigger="onBlur"
            rules={[
              { required: true, message: '请输入验证码' },
              {
                pattern: /^\d{6}$/,
                message: '验证码格式错误',
              },
            ]}
            extra={
              <span
                className="code-extra"
                onClick={timeLeft === 0 ? onGetCode : undefined}
              >
                {timeLeft === 0 ? '发送验证码' : `${timeLeft}s后重新获取`}
              </span>
            }
          >
            <Input
              maxLength={6}
              placeholder="请输入验证码"
              autoComplete="off"
            ></Input>
          </Form.Item>

          {/* noStyle 表示不提供 Form.Item 自带的样式 */}
          <Form.Item noStyle shouldUpdate>
            {() => {
              // console.log(
              //   form.isFieldsTouched(true),
              //   form.getFieldsError().filter(({ errors }) => errors.length)
              //     .length
              // )
              const disable =
                !!form.getFieldsError().filter(({ errors }) => errors.length)
                  .length || !form.isFieldsTouched(true)
              return (
                <Button
                  disabled={disable}
                  block
                  type="submit"
                  color="primary"
                  className="login-submit"
                >
                  登 录
                </Button>
              )
            }}
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login
